import SessionUtil, {JxbHttpClient} from '../../../data/session/session'
import InteractionUtil from '../../../shell/ui/interaction';
import AppSceneUtil from '../../../data/common/appScene';
import { RtLogUtil } from '../../../utils/log';
const Common = require('../../../utils/common.js');
Page({
    data: {
        showState:1,
        if_showpsd:true,
        SMCTime: 60,
        SMCTimes: true,
        SMCode_Lock: false,
        SMCode_Msg: '获取验证码',
        smsValue: '',
    },
    onLoad: function (options) {
        wx.setNavigationBarTitle({
            title: '卖酒码绑定'
        })
        Common.w_widths(this);
        InteractionUtil.showLoading(100)
        SessionUtil.getInstance().then(session=>{
            AppSceneUtil.setPageScene(this, true)
            return Promise.all([session, JxbHttpClient.getClient().get('AppMaster/ConsultantApply/applyFormSetting')])
        }).then(resp=>{
            let [session, jxbResp] = resp
            InteractionUtil.hideLoading(1000)
            let consultant_sn = wx.getStorageSync("consultant_sn")
            let renderData = {
                deploy:jxbResp.data,
                consultant_sn: consultant_sn,
                openid: session.openId,
                token : session.token
            }
            this.setData(renderData)
        
        }).catch(err=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showAlert(err.message, '请稍后再试')
        })
    },

    imageLoad: function (e) {
        this.setData({
            imageSize: Common.imageLoadAn(e, this.data.w_width).toFixed(0)
        })
    },
    /**
     * @description 检测手机号绑定情况
     * @method testPhone
     * @returns void
     *
     */
    testPhone(){
        let phone = this.data.phone, myreg = /^0?1\d{10}$/;
        try{
            if(!phone){
                throw new Error('请输入手机号码')
            } else if (!myreg.test(phone)) {
                throw new Error('手机号码格式不正确')
            }
            InteractionUtil.showLoading(300)
            JxbHttpClient.getClient().post({
                url: 'AppMaster/SellingCode/preLogin',
                data:{
                    phone: phone
                }
            }).then(jxbResp=>{
                InteractionUtil.hideLoading()
                if (jxbResp.errorCode == 302){
                    switch(jxbResp.rawResp.redirect){
                        case 'consultant/apply': //1.1没有账号，没有绑定
                            this.setData({
                                showState: 4,
                                tips: jxbResp.message
                            })
                            break;
                        case 'sellingCode/tips':
                            //1.3已有账号，手机号已经注册为其他销售商的顾问
                            //1.4手机号已经绑定当前销售商的二维码
                            this.setData({
                                showState: 3,
                                tips: jxbResp.message
                            })
                            if (jxbResp.rawResp.sellingServer){
                                this.changeConsulant(jxbResp.rawResp.sellingServer);
                            }
                            break;
                        default:
                            InteractionUtil.showAlert('系统错误，请稍后再试！未知的跳转指令：'+jxbResp.rawResp.redirect)
                            RtLogUtil.error('检测手机号状态时接口返回数据格式错误','未知的跳转指令：'+jxbResp.rawResp.redirect, jxbResp.rawResp)
                    }
                }else{
                    // 1.2已有账号，但未绑定
                    this.setData({
                        showState: 2,
                        tips: jxbResp.message
                    })
                }
            }).catch(err=>{
                InteractionUtil.hideLoading()
                InteractionUtil.showAlert(err.message, '提示')
            })
        }catch(err){
            InteractionUtil.showAlert(err.message, '提示')
        }
    },

    /**
     * @description 切换顾问
     * @method changeConsulant
     * @returns void
     *
     */
    changeConsulant: function (id) {
        InteractionUtil.showLoading()
        JxbHttpClient.getClient().post({
            url: 'AppMaster/Account/selectNewConsultant',
            data: {
                salesman_id: id
            },
        }).then(jxbResp=>{
            Common.when_user_change_clear_the_storage(()=>{
                InteractionUtil.hideLoading()
            });
        }).catch(err=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showNotice(err.message)
        })
    },

    /**
     * @description 立即申请
     * @method applicate
     * @returns void
     *
     */
    applicate() {
        let {name, phone, smsValue, consultant_sn} = this.data
        try{
            if (!name) {
                throw new Error('请输入姓名')
            }
            if (!smsValue) {
                throw new Error('请输入验证码')
            }
            InteractionUtil.showLoading(300);
            JxbHttpClient.getClient().post({
                url: 'AppMaster/ConsultantApply/apply',
                data: {
                    phone: phone,
                    realName: name,
                    sn: consultant_sn,
                    smsCode: smsValue,
                }
            }).then(jxbResp=>{
                InteractionUtil.hideLoading()
                InteractionUtil.showSuccess(jxbResp.message)
                wx.navigateTo({
                    url: '/pages/join/result/result?state=1'
                })
            }).catch(err=>{
                InteractionUtil.hideLoading()
                InteractionUtil.showAlert(err.message, '提示')
            })
        }catch(err){
            InteractionUtil.hideLoading()
            InteractionUtil.showAlert(err.message, '提示')
        }
    },

    /**
     * @description 1.2输入密码绑定
     * @method bindAccount
     * @returns void
     *
     */
    bindAccount: function (e) {
        let {phone:userName, normalPwD:passWord, openid} = this.data
        try{
            if (!passWord) {
                throw new Error('请输入密码')
            }
            JxbHttpClient.getClient().post({
                url: 'AppMaster/Login/login',
                data: {
                    userName: userName,
                    password: passWord,
                    openid: openid,
                },
            }).then(jxbResp=>{
                this.bindFunction(jxbResp.rawResp.token);
            }).catch(err=>{
                InteractionUtil.showAlert(err.message, '提示')
            })
        }catch(err){
            InteractionUtil.showAlert(err.message)
        }
        
    },

    /**
     * @description 验证码登录
     * @method SMS_login
     * @returns void
     *
     */
    SMS_login() {
        InteractionUtil.showLoading(300)
        JxbHttpClient.getClient().post({
            url: '/AppMaster/Login/checkMessageCodeLogin',
            data: {
                phone: this.data.phone,
                code: this.data.smsValue,
            },
        }).then(jxbResp=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showSuccess('短信已经发送')
            this.bindFunction(jxbResp.data.token);
        }).catch(err=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showAlert(err.message).then(()=>{
                this.setData({
                    SMCTime: 60,
                    SMCode_Lock: false,
                    SMCode_Msg: '获取验证码',
                    SMCTimes: true,
                })
            })
        })
    },

    /**
     * @description 提交绑定卖酒码请求
     * @method bindFunction
     * @returns void
     *
     */
    bindFunction(login_token){
        JxbHttpClient.getClient().post({
            url: 'AppMaster/SellingCode/doBindWithServer',
            data: {
                sn: this.data.consultant_sn,
                token: login_token
            }
        }).then(jxbResp=>{
            wx.navigateTo({
                url: '/pages/join/result/result?state=2'
            })
        }).catch(err=>{
            InteractionUtil.showAlert(err.message, '提示').then(()=>{
                this.toIndex()
            })
        })
    },

    /**
     * @description 获取手机号验证码
     * @method getSMS
     * @returns void
     *
     */
    getSMS: function (e) {
        let phone = this.data.phone;
        this.setData({
            SMCode_Lock: true
        });
        InteractionUtil.showLoading(300)
        JxbHttpClient.getClient().post({
            url: '/AppMaster/Login/bindPhoneSendMessageCode',
            data: {
                phone: phone
            }
        }).then(jxbResp=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showSuccess('验证码已发送').then(()=>{
                // 倒计时显示
                this.SMCode_Msg();
            })  
        }).catch(err=>{
            InteractionUtil.hideLoading()
            InteractionUtil.showAlert(err.message, '提示').then(()=>{
                this.setData({
                    SMCTime: 60,
                    SMCode_Lock: false,
                    SMCode_Msg: '获取验证码'
                })
            })
        })
    },

    SMCode_Msg: function () {
        let {SMCTime, SMCode_Msg, SMCode_Lock} = this.data, SMCTimers
        if (SMCTime > 1) {
            SMCTime--;
            SMCode_Msg = '重新获取(' + SMCTime + ')';
            this.setData({
                SMCTime: SMCTime,
                SMCode_Msg: SMCode_Msg,
                SMCTimes: false,
                SMCode_Lock: true
            })
            // 定时器执行
            SMCTimers = setTimeout(()=>{
                this.SMCode_Msg()
            }, 1000);

        } else {
            clearTimeout(SMCTimers);
            this.setData({
                SMCTime: 60,
                SMCode_Lock: false,
                SMCode_Msg: '获取验证码',
                SMCTimes: true,
            })
        }
    },

    /**
     * @description 去首页
     * @method toIndex
     * @returns void
     *
     */
    toIndex(){
        wx.switchTab({
            url: '/pages/index/index',
        })
    },

    /**
     * @description 手机号验证码登录
     * @method hidepsd
     * @returns void
     *
     */
    hidepsd(){
        this.setData({
            if_showpsd:false
        })
    },

    showpsd() {
        this.setData({
            if_showpsd: true
        })
    },

    //更新手机号输入框的值
    updatePhone: function (e) {
        this.setData({
            phone: e.detail.value
        })
    },

    //更新用户姓名
    changeName: function (e) {
        this.setData({
            name: e.detail.value
        })
    }, 
    
    //更新验证码
    changeSMS: function (e) {
        this.setData({
            smsValue: e.detail.value
        })
    },

    //更新密码
    updatePwd: function (e) {
        this.setData({
            normalPwD: e.detail.value
        })
    },

    onPullDownRefresh: function () {
        wx.stopPullDownRefresh()
    },
    
})